﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections;
using System.ComponentModel.Design.Serialization;
using System.Reflection;

namespace ZDT.Design
{
    public class DictionaryTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(String)) return true;
            return base.CanConvertFrom(context, sourceType);
        }
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(String)) return true;
            if (destinationType == typeof(InstanceDescriptor)) return true;
            return base.CanConvertTo(context, destinationType);
        }
        public override object ConvertTo(ITypeDescriptorContext context,
            System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            String result = "";
            if (destinationType == typeof(string))
            {
                IDictionary scope = (IDictionary)value;
                foreach (var item in scope)
                {
                    //result += string.Format("({0},{1})", item.Key, item.Value);
                }
                return result;
            }
            if (destinationType == typeof(InstanceDescriptor))
            {
                ConstructorInfo ci = typeof(IDictionary).GetConstructor(new Type[] { typeof(Int32), typeof(Int32) });
                IDictionary scope = (IDictionary)value;
                return new InstanceDescriptor(ci, new object[] { scope });
            } 
            return base.ConvertTo(context, culture, value, destinationType);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                String[] v = ((String)value).Split(',');
                if (v.GetLength(0) != 2)
                {
                }
                IDictionary csf = new Dictionary<string, string>();
                return csf;
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override bool GetPropertiesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {
            return TypeDescriptor.GetProperties(typeof(KeyValuePair<,>), attributes);
        } 
    }

}
